const Router = require("koa-router");
const router = new Router({ prefix: "/set/" });
const { getFile, setFile } = require("../utils/index");

// 设置文件信息
router.post("nav", (ctx, next) => {
  const filePath = "../data/nav.json";
  const { modo, indexPathList, currentIndex, data, editType } =
    ctx.request.body;

  const nav = JSON.parse(getFile(filePath));
  let operationNavList = {
    list: nav,
  };
  indexPathList
    .split(",")
    .forEach((index) => (operationNavList = operationNavList.list[index]));

  switch (modo) {
    case "add":
      if (editType === "nav") {
        operationNavList.list.push(data);
      } else {
        operationNavList.list.push({ label: data, list: [] });
      }
      break;
    case "edit":
      if (editType === "nav") {
        operationNavList.list[currentIndex] = data;
      } else {
        operationNavList.list[currentIndex].label = data;
      }
      break;
    case "del":
      operationNavList.list.splice(currentIndex, 1);
      break;
    default:
      break;
  }

  setFile(filePath, JSON.stringify(nav));
  ctx.response.status = 200; // 设置响应状态码
  ctx.response.type = "application/json"; // 设置响应类型
  ctx.response.body = {
    status: 200,
    success: true,
    message: "请求成功",
    data: "收到请求",
  };
});

module.exports = router;
